import React, {useEffect, useState} from 'react'
import {Form, Button, DatePicker, Modal, Row, Col, Cascader, Input, message, Tag, Table} from 'antd'
import moment from 'moment'
import {connect} from 'umi'
import {contractTempList, leavingReasonTree} from '@/utils/constant'
import {getPersonRecord} from "@/pages/Contract/service";

const FormItem = Form.Item;
const { TextArea } = Input;

const formLayout = {
  labelCol: {span: 7},
};

const CreateForm = (props) => {
  const {visible, onSubmit, onCancel, current} = props;
  const [form] = Form.useForm();
  const [showOtherReason, setShowOtherReason] = useState(false);
  const [leavingText, setLeavingText] = useState('');
  const [contractData, setContractData] = useState([]);

  const contractColumns = [
    {title: '合同主体', dataIndex: 'employerCompany', align: 'center'},
    {
      title: '生效日期', dataIndex: 'contractBeginDate', align: 'center',
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '终止日期', dataIndex: 'contractEndDate', align: 'center',
      render: (text) => {
        return text !== '-' ? moment(text).format('YYYY-MM-DD') : ''
      }
    },
    {
      title: '合同类型', dataIndex: 'beginContractType',align: 'center',
      render: (text) => {
        return contractTempList.find((item) => item.value === parseInt(text))?.label;
      },
    },
    {
      title: '合同状态', dataIndex: 'status',align: 'center',
      render:() => {
        return (<Tag color="green">已生效</Tag>);
      }
    },
  ];


  useEffect(() => {
    if (visible) {
      getPersonRecord(current.oid).then(res => {
        setContractData([res]);
      });
    }
  }, [visible]);

  const onFormCancel = () => {
    setContractData([]);
    form.resetFields();
    onCancel();
  };

  const handleNext = async () => {
    const fieldsValue = await form.validateFields();
    let reason = {
      reason: fieldsValue.remark.toString(),
      otherReason: fieldsValue.otherRemark ? fieldsValue.otherRemark : '',
      reasonText: fieldsValue.otherRemark ? fieldsValue.otherRemark : leavingText
    };
    onSubmit({id: current.id, processingStatus: 2, dimissionTime: moment(fieldsValue.dimissionTime).format('YYYY-MM-DD'), reason: JSON.stringify(reason)});
    form.resetFields();
  };


  const setReasonForLeaving = (label) =>{
    if (typeof label !== 'string'){
      setLeavingText(label.join(' / '));
      return label.join(' / ');
    }else {
      setLeavingText(label.join(' / '));
      return [label].join(' / ');
    }
  };

  const changeReason = (value) =>{
    if (value.length>0 && value[0] === 3){
      setShowOtherReason(true);
      form.setFieldsValue({otherRemark: ''});
    }else {
      setShowOtherReason(false);
    }
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24} justify='center'>
          <Col span={18}>
            <FormItem name="dimissionTime" labelCol={{span: 5}} label="离职日期" rules={[{required: true, message: '请选择离职日期'}]}>
              <DatePicker className='widthStyle'/>
            </FormItem>
          </Col>
          <Col span={18}>
            <FormItem name="remark" labelCol={{span: 5}} label="离职原因" rules={[{required: true, message: '离职原因不能为空！'}]}>
              <Cascader options={leavingReasonTree} onChange={changeReason} displayRender={(label) => setReasonForLeaving(label)} placeholder="请选择原因" />
            </FormItem>
          </Col>
          {
            showOtherReason && <>
              <Col span={18}>
                <FormItem name="otherRemark" labelCol={{span: 5}} label="其他原因说明"
                          rules={[{required: true, message: '其他原因说明不能为空！'}]}>
                  <TextArea rows={4}/>
                </FormItem>
              </Col>
            </>
          }
        </Row>
      </>
    )
  };

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" onClick={() => handleNext()}>完成</Button>
      </>
    )
  }

  return (
    <Modal
      width='70%'
      destroyOnClose
      title="离职原因填写"
      visible={visible}
      footer={renderFooter()}
      onOk={handleNext}
      onCancel={onFormCancel}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
      >
        {renderContent()}
      </Form>
      <Table
        style={{marginBottom: 24}}
        title={() => '合同信息'}
        rowKey="id"
        size="small"
        bordered
        pagination={false}
        dataSource={contractData}
        columns={contractColumns}
      />
    </Modal>
  )
}

export default connect(({}) => ({

}))(CreateForm)
